package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    private final WmNewsMaterialMapper wmNewsMaterialMapper;

    private final WmMaterialMapper wmMaterialMapper;

    private final WmNewsMapper wmNewsMapper;

    private final WmNewsTaskService wmNewsTaskService;

    private final WmUserMapper wmUserMapper;

    private final WmNewsAutoScanService wmNewsAutoScanService;


    private final KafkaTemplate kafkaTemplate;


    /**
     * 文章审核失败 或者通过
     *
     * @param newsAuthDto
     * @return
     */
    @Override
    public ResponseResult wmNewsAuthFailOrPass(NewsAuthDto newsAuthDto) {
        // 1、检查参数
        if (newsAuthDto == null || newsAuthDto.getStatus() == null || newsAuthDto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2、更新 wm_news表
        WmNews wmNews = new WmNews();
        wmNews.setId(newsAuthDto.getId());
        if (newsAuthDto.getStatus().equals(WmNews.Status.ADMIN_SUCCESS.getCode())) {
            // 保存文章端的文章数据
            // 查询自媒体文章数据
            wmNews = wmNewsMapper.getNews(wmNews);
            ResponseResult responseResult = wmNewsAutoScanService.saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)) {
                throw new RuntimeException("WmNewsServiceImpl-文章人工审核，保存app端相关文章数据失败");
            }
        }
        wmNews.setStatus(newsAuthDto.getStatus());
        wmNews.setReason(newsAuthDto.getMsg());
        wmNewsMapper.updateWmNews(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据 文章id 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult getNewsVoById(Integer id) {
        // 1、查询文章
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        wmNews = wmNewsMapper.getNews(wmNews);
        // 2、转vo
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, wmNewsVo);
        // 3、查询作者名字
        WmUser wmUser = new WmUser();
        wmUser.setId(wmNews.getUserId());
        wmUser = wmUserMapper.selectUser(wmUser);
        // 4、设置作者名字
        wmNewsVo.setAuthorName(wmUser.getName());
        return ResponseResult.okResult(wmNewsVo);
    }

    /**
     * 自媒体文章人工审核列表
     *
     * @param newsAuthDto
     * @return
     */
    @Override
    public ResponseResult listManualCheckNews(NewsAuthDto newsAuthDto) {
        // 1、检查参数
        if (newsAuthDto == null || newsAuthDto.getPage() <= 0 || newsAuthDto.getSize() <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        newsAuthDto.setPage((newsAuthDto.getPage() - 1) * newsAuthDto.getSize());
        // 2、查询文章列表 信息
        List<WmNews> wmNewsList = wmNewsMapper.listManualCheckNews(newsAuthDto);
        // 3、查询作者名字
        List<WmNewsVo> wmNewsVoList = wmNewsList.stream().map(wmNews -> {
            WmNewsVo wmNewsVo = new WmNewsVo();
            BeanUtils.copyProperties(wmNews, wmNewsVo);

            WmUser wmUser = new WmUser();
            wmUser.setId(wmNews.getUserId());
            wmUser = wmUserMapper.selectUser(wmUser);

            wmNewsVo.setAuthorName(wmUser.getName());
            return wmNewsVo;
        }).collect(Collectors.toList());

        return ResponseResult.okResult(wmNewsVoList);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        log.info("修改文章状态dto{}", dto);
        // 1、检查参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章ID不可缺少");
        }

        // 2、查询文章
        WmNews wmNews = getById(dto.getId());

        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能上下架");
        }

        // 更新自媒体端wmnews表上下架状态
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {

            wmNews.setEnable(dto.getEnable());
            updateById(wmNews);
            if (wmNews.getArticleId() != null) {
                log.info("kafka异步发送消息：{}文章上下架{}", wmNews.getArticleId(), wmNews.getEnable());
                // TODO更新app端article_config表的上下架状态(异步) 使用kafka
                Map<String, Object> map = new HashMap<>();
                map.put("articleId", wmNews.getArticleId());
                map.put("enable", dto.getEnable());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "参数错误");


    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public ResponseResult deleteNewsById(Integer id) {
        log.info("删除文章，文章id{}", id);
        // 1、检查参数
        if (id == null) {
            return ResponseResult.errorResult(501, "文章ID不可缺少");
        }

        // 2、删除文章表中的数据
        WmNews wmNews = wmNewsMapper.selectOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id));

        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已发布文章不可删除");
        }
        wmNewsMapper.deleteById(wmNews.getId());
        // 3、删除该文章与素材的关系表的数据

        // 不是草稿要删除 文章与素材关系 是草稿则不用
        if (!wmNews.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, id));
        }
        // 4、返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult getNewsById(Integer id) {
        log.info("查询文章，文章id{}", id);
        // 1、查询数据库
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getId, id));

        // 2、检查参数
        if (wmNews == null) {
            return ResponseResult.errorResult(1002, "文章不存在");
        }
        // 3、返回结果
        return ResponseResult.okResult(wmNews);
    }

    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        log.info("查询文章dto{}", dto);
        // 1、参数检验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 分页参数检查
        dto.checkParam();
        // 当前登录用户检查
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2、分页条件查询
        // 构造分页条件
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //频道精确查询
        //状态精确查询
        //时间范围查询
        //关键字模糊查询
        //当前登陆人精确查询
        //发布时间倒叙
        lambdaQueryWrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId())
                .eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus())
                .between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null,
                        WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate())
                .like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword())
                .eq(WmNews::getUserId, user.getId())
                .orderByDesc(WmNews::getPublishTime);


        page = wmNewsMapper.selectPage(page, lambdaQueryWrapper);
        // 3、结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        // 0、条件判断
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 1、保存或修改文章
        // 属性拷贝
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        // 封面图片 list --> String
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String imageStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imageStr);
        }
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }

        saveOrUpdateWmNews(wmNews);
        // 2、判断是否为草稿，如果为草稿则结束该方法
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        // 3、不是草稿，保存文章内容图片与素材的关系
        //获取到文章内容中的图片信息
        List<String> materials = ectractUrlInfo(dto.getContent());
        saveRelativeInfoForContent(materials, wmNews.getId());

        // 4、不是草稿，保存文章封面图片与素材的关系 当前布局是自动，需要自动匹配封面图片
        saveRelativeInfoForCover(dto, wmNews, materials);

        // 5、添加 任务
        //  wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 第一个功能，如果当前封面类型为自动，则设置封面类型的数据
     * 匹配规则：
     * 1，如果内容图片大于等于1，小于3  单图  type 1
     * 2，如果内容图片大于等于3  多图  type 3
     * 3，如果内容没有图片，无图  type 0
     *
     * @param dto
     * @param wmNews
     * @param materials
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        // 拿到封面集合
        List<String> images = dto.getImages();

        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {

            if (materials.size() >= 3) { //多图
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else if (materials.size() >= 1) { //单图
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else { //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

        }
        if (images != null && images.size() > 0) {
            wmNews.setImages(StringUtils.join(images, ","));
        }
        // 更新数据
        updateById(wmNews);

        if (images != null && images.size() > 0) {
            //保存封面图片与素材的关系
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    /**
     * 处理文章内容中的图片与素材的关系表
     *
     * @param materials
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存文章图片与素材的关系到数据库中
     *
     * @param materials
     * @param newsId
     * @param wmContentReference
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short wmContentReference) {

        if (materials != null && !materials.isEmpty()) {
            //批量保存
            // 通过图片的url查询素材id
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                    .in(WmMaterial::getUrl, materials));
            //判断素材是否有效
            if (wmMaterials == null || wmMaterials.size() == 0) {
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }

            if (materials.size() != wmMaterials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }

            // 只需要id，使用stream
            List<Integer> wmMaterialIds = wmMaterials.stream().map(WmMaterial::getId
            ).collect(Collectors.toList());
            wmNewsMaterialMapper.saveRelations(wmMaterialIds, newsId, wmContentReference);
        }

    }

    /**
     * 提取文章内容中的图片信息
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> materials = new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                String imgUrl = (String) map.get("value");
                materials.add(imgUrl);
            }
        }
        return materials;
    }


    private void saveOrUpdateWmNews(WmNews wmNews) {
        // 补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setPublishTime(new Date());
        wmNews.setEnable((short) 1); // 默认上架

        if (wmNews.getId() == null) {
            // 保存
            save(wmNews);
        } else {
            //修改
            // 删除文章图片与素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }
}
